package services;

import dao.ApplyInfo_Repository;
import models.*;
import org.apache.commons.lang.StringUtils;
import play.db.jpa.JPAApi;

import javax.inject.Inject;
import javax.persistence.Query;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletionStage;

import static java.util.concurrent.CompletableFuture.supplyAsync;


/**
 * Provide JPA operations running inside of a thread pool sized to the connection pool
 */
public class ApplyInfo_Repository_JPA implements ApplyInfo_Repository {

    private final JPAApi jpaApi;
    private final DatabaseExecutionContext executionContext;

    @Inject
    public ApplyInfo_Repository_JPA(JPAApi jpaApi, DatabaseExecutionContext executionContext) {
        this.jpaApi = jpaApi;
        this.executionContext = executionContext;
    }

    @SuppressWarnings("unchecked")
    @Override
    public CompletionStage<List<ApplyInfo_C_Entity>> getApplyList (String StartDate, String EndDate, String PhoneNumber, String AuditStatus, String productName)
    {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
                //return entityManager.createQuery("select c from ApplyInfo_T_Entity c ", ApplyInfo_T_Entity.class).getResultList();
                String strSql = "select * from dbo.f_getApplyList('"+ StartDate +"','" + EndDate + "','" + PhoneNumber + "','" + AuditStatus + "','"+productName+"') as a left join t_UserRoute as b on a.fd_ApplyID = b.applicationId order by fd_ApplyID desc";
                //String strSql = "select * from dbo.f_TableApplyInfo(GETDATE(),'" + EndDate + "','" + ConTractNum + "','" + Deliveryid + "','"+ KHMC +"','" + HWMC + "','"+ Status +"') as ApplyInfo";
                return entityManager.createNativeQuery(strSql, ApplyInfo_C_Entity.class).getResultList();
            });
        }, executionContext);
    }
    
    @SuppressWarnings("unchecked")
	@Override
    public CompletionStage<List<ApplyInfo_C_Entity>> getApplyInfoList (String StartDate, String EndDate, String PhoneNumber, String AuditStatus)
    {
    	return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
            	//return entityManager.createQuery("select c from ApplyInfo_T_Entity c ", ApplyInfo_T_Entity.class).getResultList();
            	String strSql = "select * from dbo.f_TabApplyInfo('"+ StartDate +"','" + EndDate + "','" + PhoneNumber + "','" + AuditStatus + "') as a left join t_UserRoute as b on a.fd_ApplyID = b.applicationId order by fd_ApplyID desc";
            	//String strSql = "select * from dbo.f_TableApplyInfo(GETDATE(),'" + EndDate + "','" + ConTractNum + "','" + Deliveryid + "','"+ KHMC +"','" + HWMC + "','"+ Status +"') as ApplyInfo";
            	return entityManager.createNativeQuery(strSql, ApplyInfo_C_Entity.class).getResultList();
            });
        }, executionContext);    	
    }
    
    @SuppressWarnings("unchecked")
	@Override
	/*public CompletionStage<List<Object>> CreatNewApply(List<JsonNode> PhoneNumberList, List<JsonNode> fd_DeliveryOrderidList, List<JsonNode> fd_SubIdList, List<JsonNode> TruckNoList, List<JsonNode> DeliveryDateList, List<JsonNode> DeliveryQtyList, List<JsonNode> UnLoadPlaceList, List<JsonNode> CirCleTimeList) {


		return supplyAsync(() -> {
			return jpaApi.withTransaction((EntityManager entityManager) -> {
				// 插入一个原生SQL的测试,调用了SQLServer的自定义函数.
//                String strSql = null;
				String  a="添加成功";
				List<Object> res = new ArrayList<Object>();
				res.add(a);
				List<Object> ApplyInfo_T_Entity=null;

				for (int i = 0, j = TruckNoList.get(0).size(); i < j; i++) {
					String TruckNo = TruckNoList.get(0).get(i).toString().substring(1, TruckNoList.get(0).get(i).toString().length() - 1);
					String PhoneNumber = PhoneNumberList.get(0).get(0).toString().substring(1, PhoneNumberList.get(0).get(0).toString().length() - 1);
//                        System.out.println("列表的大小2"+PhoneNumber);

					String fd_SubId = fd_SubIdList.get(0).get(0).toString().substring(1, fd_SubIdList.get(0).get(0).toString().length() - 1);
					String DeliveryDate = DeliveryDateList.get(0).get(0).toString().substring(1, DeliveryDateList.get(0).get(0).toString().length() - 1);
					String DeliveryQty = DeliveryQtyList.get(0).get(0).toString().substring(1, DeliveryQtyList.get(0).get(0).toString().length() - 1);
					String UnLoadPlace = UnLoadPlaceList.get(0).get(0).toString().substring(1, UnLoadPlaceList.get(0).get(0).toString().length() - 1);
					String CirCleTime = CirCleTimeList.get(0).get(0).toString().substring(1, CirCleTimeList.get(0).get(0).toString().length() - 1);
					String fd_DeliveryOrderid=fd_DeliveryOrderidList.get(0).get(0).toString().substring(1, fd_DeliveryOrderidList.get(0).get(0).toString().length() - 1);
//                    System.out.println("单号"+TruckNoList.get(0).size());
					String strSql = "exec p_CreateNewApply @PhoneNumber = '" + PhoneNumber + "',@fd_DeliveryOrderid = '"
							+ fd_DeliveryOrderid + "', @fd_SubId = '"
							+ fd_SubId + "', @TruckNo ='"
							+ TruckNo + "', @DeliveryDate ='"
							+ DeliveryDate + "', @DeliveryNum ="
							+ DeliveryQty + ", @UnLoadPlace ='"
							+ UnLoadPlace + "', @CirCleTime ="
							+ CirCleTime + " ";

//                        System.out.println("单号" + strSql);
//            	return entityManager.createNativeQuery(strSql, ApplyInfo_T_Entity.class).getResultList();
					ApplyInfo_T_Entity =  entityManager.createNativeQuery(strSql, ApplyInfo_T_Entity.class).getResultList();

				}
				if (ApplyInfo_T_Entity.size() != 0) {
					return res;
				}


				String PhoneNumber = PhoneNumberList.get(0).get(0).toString().substring(1, PhoneNumberList.get(0).get(0).toString().length() - 1);
//                System.out.println("单号"+PhoneNumber);
				String strSql2 = "select * from f_GetLastErr('" + PhoneNumber + "') ";
				return entityManager.createNativeQuery(strSql2, ErrorLog_T_Entity.class).getResultList();

			});
		}, executionContext);


	}*/
	public CompletionStage<List<Object>> CreatNewApply(String PhoneNumber,String fd_DeliveryOrderid, String fd_SubId, String TruckNo, String DeliveryDate, String DeliveryQty , String UnLoadPlace , String CirCleTime)
	{
		return supplyAsync(() -> {
			return jpaApi.withTransaction(entityManager -> {
				// 插入一个原生SQL的测试,调用了SQLServer的自定义函数.
				String strSql = "exec p_CreateNewApply @PhoneNumber = '" + PhoneNumber + "',@fd_DeliveryOrderid = '"
						+ fd_DeliveryOrderid + "', @fd_SubId = '"
						+ fd_SubId + "', @TruckNo ='"
						+ TruckNo +  "', @DeliveryDate ='"
						+ DeliveryDate +  "', @DeliveryNum ="
						+ DeliveryQty + ", @UnLoadPlace ='"
						+ UnLoadPlace + "', @CirCleTime ="
						+ CirCleTime + " ";
//            	return entityManager.createNativeQuery(strSql, ApplyInfo_T_Entity.class).getResultList();

				List<ApplyInfo_T_Entity> list =
						entityManager.createNativeQuery(strSql, ApplyInfo_T_Entity.class).getResultList();

				if(list.size() != 0) {
					String  a="添加成功";
					List<Object> res = new ArrayList<Object>();
					res.add(a);
					return res;

				}else {
					String strSql2 = "select * from f_GetLastErr('" + PhoneNumber + "') ";
					return entityManager.createNativeQuery(strSql2, ErrorLog_T_Entity.class).getResultList();
				}
			});
		}, executionContext);
	}

	@SuppressWarnings("unchecked")
	@Override
	public CompletionStage<String> aduit (String applicationId,String result,String reason,Long bookTime)
	{
		return supplyAsync(() -> {
			return jpaApi.withTransaction(entityManager -> {

				if (applicationId == null
						|| result == null
						|| (Integer.valueOf(result) !=1 && Integer.valueOf(result) != 2)) {
					return "请正确填写后重试";
				}
			    if (Integer.valueOf(result) == 2) {
					if (StringUtils.isBlank(reason)) {
						return "不通过，须填写不通过原因";
					}
				}
				ApplyInfo_T_Entity tApplyInfoEntity = entityManager.find(
						ApplyInfo_T_Entity.class, Integer.valueOf(applicationId));
				if (tApplyInfoEntity == null) {
					return "入厂申请单不存在";
				}

				// 已通过或已完成，返回success
				if (tApplyInfoEntity.getFd_AuditStatus() != null
						&& (Integer.valueOf(tApplyInfoEntity.getFd_AuditStatus()) == 1 || Integer.valueOf(tApplyInfoEntity.getFd_AuditStatus())  == 3)) {
					return "成功";
				}

				tApplyInfoEntity.setFd_AuditStatus(result);
				if (StringUtils.isNotEmpty(reason)) {
					tApplyInfoEntity.setFd_AuditReason(reason);
				}

				Timestamp nowTimeStamp = new Timestamp(System.currentTimeMillis());
				// 预约入厂的时间
				Timestamp deliDate;
				if (bookTime == null) {
					deliDate = nowTimeStamp;
				} else {
					// api定义是unix时间戳
					deliDate = new Timestamp(new Date(bookTime * 1000).getTime());
				}
				tApplyInfoEntity.setFd_DeliDate(deliDate.toString());
				tApplyInfoEntity.setFd_AuditDate(nowTimeStamp.toString());

				entityManager.persist(tApplyInfoEntity);

				// 初始化行程记录
				// 审核通过后再初始化，避免产生很多无效的行程数据
				if (Integer.valueOf(result) == 1) {
					UserRoute_T_Entity userRouteEntity = new UserRoute_T_Entity();
					userRouteEntity.setStatus(0);
					userRouteEntity.setUserId(tApplyInfoEntity.getFd_ApplicantID());
					userRouteEntity.setApplicationId(tApplyInfoEntity.getFd_ApplyID());
					userRouteEntity.setCreateTime(nowTimeStamp);
					userRouteEntity.setModifyTime(nowTimeStamp);
					entityManager.persist(userRouteEntity);
				}
				return  "成功";
			});
		}, executionContext);
	}

	public CompletionStage<String> cancleApply (Integer ApplyID)
	{
		return supplyAsync(() -> {
			return jpaApi.withTransaction(entityManager -> {
				Query query = entityManager.createQuery("update ApplyInfo_T_Entity d set d.fd_AuditStatus = 2 where d.fd_ApplyID=:applyInId ");

				query.setParameter("applyInId", ApplyID);
				query.executeUpdate();
				return "成功";
			});
		}, executionContext);
	}

	@SuppressWarnings("unchecked")
	@Override
	public CompletionStage<List<Result_Entity>> pcancleApply(String PhoneNumber, String ApplyNumber) {
		return supplyAsync(() -> {
			return jpaApi.withTransaction(entityManager -> {
				String strSql = "exec p_CancleApply @PhoneNumber = '"+ PhoneNumber +"',@ApplyNumber = '"+ ApplyNumber +"' ";
				return entityManager.createNativeQuery(strSql, Result_Entity.class).getResultList();
			});
		}, executionContext);
	}

	@Override
	public CompletionStage<List<XMLString_Entity>> AuditApplyBatch(String PhoneNumber, String ApplyIDs) {
		return supplyAsync(() -> {
			return jpaApi.withTransaction(entityManager -> {
				String strSql = "exec p_AuditApplyBatch @PhoneNumber = '"+ PhoneNumber +"',@ApplyIDs = '"+ ApplyIDs +"' ";
				return entityManager.createNativeQuery(strSql, XMLString_Entity.class).getResultList();
			});
		}, executionContext);
	}

	@Override
	public CompletionStage<List<XMLString_Entity>> cancleApplyBatch(String PhoneNumber, String ApplyIDs, String reason) {
		return supplyAsync(() -> {
			return jpaApi.withTransaction(entityManager -> {
				String strSql = "exec p_CancleApplyBatch @PhoneNumber = '"+ PhoneNumber +"',@ApplyIDs = '"+ ApplyIDs +"',@reason = '"+reason+"' ";
				return entityManager.createNativeQuery(strSql, XMLString_Entity.class).getResultList();
			});
		}, executionContext);
	}

}